package com.elite.groovy.callback

import com.elite.groovy.davco.clink.ClinkUtils
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: apiClinkCdrRecord
 * @description: 同步天润IB呼入&OB呼出记录数据
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */

public class apiClinkQueueAgents implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiClinkQueueAgents.class);

    private static boolean isRun = true;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        try {

            // 获取数据源
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 先标记无效
            jt.update("Update Clink_Queue_List Set Status = 0");
            jt.update("Update Clink_Queueagent_List Set Status = 0");

            // 同步IB呼入数据
            int Offset = 0;
            isRun = true;
            log.debug("同步QueueAgents数据...");
            while (isRun && Offset < 1000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("同步QueueAgents数据...偏移Offset:" + Offset);
                toDoQueueGet(jt, Offset * 100);
                Offset = Offset + 1;
            }

            log.debug("QueueAgents同步任务结束执行...");
        } catch (Exception e) {
            log.error("HTTP请求调用错误，QueueAgents 处理异常：" + e.getMessage());
            return e.getMessage();

        }

        return "SUCC";

    }

    // 1-同步队列列表
    static toDoQueueGet(JdbcTemplate jt, int Offset) {

        //处理主数据
        log.debug("1-同步队列列表 toDoGet Data Offset:" + Offset);

        // 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/list_queues?";

        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("offset", String.valueOf(Offset));
        queryParams.put("limit", "100");
        log.debug("1-同步队列列表 queryParams:" + queryParams);

        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        log.debug("1-同步队列列表 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        log.debug("1-同步队列列表 Data Result:" + doGETJSON);

        JSONArray dataArray = doGETJSON.getJSONArray("queues"); ;
        int dataArrayLen = dataArray.size();
        log.info("1-同步队列列表 Data Result size:" + dataArrayLen);

        if (dataArrayLen <= 0) {
            isRun = false;
        }

        JSONObject dataObject = null;
        String sql = null;
        for (int i = 0; i < dataArrayLen; i++) {
            dataObject = dataArray.getJSONObject(i);
            String id = KHUtil.GetSFJV(dataObject, "id");
            String qno = KHUtil.GetSFJV(dataObject, "qno");
            String name = KHUtil.GetSFJV(dataObject, "name");
            String omniClientNum = KHUtil.GetSFJV(dataObject, "omniClientNum");
            String callClientNum = KHUtil.GetSFJV(dataObject, "callClientNum");
            String chatClientNum = KHUtil.GetSFJV(dataObject, "chatClientNum");

            sql = '''Replace Into Clink_Queue_List
              (Id, Qno, Name, Omniclientnum, Callclientnum, Chatclientnum, Sync_Time, Status)
            Values
              (?, ?, ?, ?, ?, ?, Now(), 1)''';

            jt.update(sql, id, qno, name, omniClientNum, callClientNum, chatClientNum);

            toDoQueueAgent(jt, qno);
        }

    }

    // 2-同步队列详情(关系)
    static toDoQueueAgent(JdbcTemplate jt, String qno) {

        //处理主数据
        log.debug("2-同步队列详情(关系) toDoGet Data qno:" + qno);

        // 封装调用头Heads
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");

        // 系统接入-GET
        String getPath = "/cc/describe_queue?";

        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("qno", qno);
        log.debug("2-同步队列详情(关系) queryParams:" + queryParams);

        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        log.debug("2-同步队列详情(关系) doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        log.debug("2-同步队列详情(关系) Data Result:" + doGETJSON);

        if (doGETJSON.containsKey("queue") && doGETJSON.getJSONObject("queue").containsKey("queueMembers")) {
            JSONArray dataArray = doGETJSON.getJSONObject("queue").getJSONArray("queueMembers"); ;
            int dataArrayLen = dataArray.size();
            log.info("2-同步队列详情(关系) Data Result size:" + dataArrayLen);

            JSONObject dataObject = null;
            String sql = null;
            for (int i = 0; i < dataArrayLen; i++) {
                dataObject = dataArray.getJSONObject(i);
                String cno = KHUtil.GetSFJV(dataObject, "cno");
                String penalty = KHUtil.GetSFJV(dataObject, "penalty");
                String type = KHUtil.GetSFJV(dataObject, "type");

                sql = '''Replace Into Clink_QueueAgent_List
                      (Qno, Cno, penalty, Type, Sync_Time, Status)
                    Values
                      (?, ?, ?, ?, Now(), 1)''';

                jt.update(sql, qno, cno, penalty, type);
            }
        } else {

            log.warn("2-同步队列详情(关系) Data Result 为空或异常");
        }

    }

}